'use strict';
const fs = require('fs')
const path = require('path');
const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');
const { Controller } = require('egg');

class upLoadController extends Controller {
    async index() {
        const { ctx } = this;
        const stream = await ctx.getFileStream();
        console.log(stream)
        const name =ctx.helper.getNowDate()+path.basename(stream.filename);
        const target=path.join('','app/public/upload/img',name)
        const wirteStream=fs.createWriteStream(target)
        let imgurl='public/upload/img/'+name;
        // 文件处理，上传到云存储等等
        try {
            await awaitWriteStream(stream.pipe(wirteStream));
        } catch (err) {
            // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
            await sendToWormhole(stream);
            throw err;
        }
        ctx.body = imgurl;
    }
    //获取图片
    async getImg() {
        const ctx = this.ctx;
        try {
            //这里将文件夹下的所有图片都读出了，实际上应该是从数据库中得到图片路径
            //在从imgBaseUrl中获得相应的图片完整路径，使用fs.readFileSync("完整的图片路径", 'base64');将图片转为base64格式，
            let files = fs.readdirSync('app/public/upload/img');//读取该文件夹

            let imgArr = [];
            files.forEach((file) => {
                //把每个图片都转为base64格式
                let base64 = fs.readFileSync('app/public/upload/img' + '/' + file, 'base64');
                imgArr.push(base64);
            })
            return ctx.body = {
                status: 1,
                data: imgArr //将base64图片数组传给前端，到前端的时候再将base64转成图片显示
            }
        } catch (error) {
            console.log(error)
            return ctx.body = {
                status: 0,
            }
        }
    }
}

module.exports = upLoadController;
